package com.chansos.dubbogo.util;

import java.io.*;
import java.util.Map;

public class TemplateUtils {
    public static String replaceContent(String content, Map<String, String> args) {
        for (Map.Entry<String, String> keyValue : args.entrySet()) {
            content = content.replace(keyValue.getKey(), keyValue.getValue());
        }
        return content;
    }

    public static String readTemplate(String path) {
        InputStream stream = ResourceUtils.getResource(path);
        if (stream == null) {
            return null;
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
        try {
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line).append('\n');
            }
            reader.close();
            return stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                stream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void writeTemplate(String path, String content) {
        BufferedWriter writer = null;
        try {
            File file = new File(path);
            file.getParentFile().mkdirs();
            writer = new BufferedWriter(new FileWriter(file));
            writer.write(content);
            writer.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                assert writer != null;
                writer.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
